package cn.llyong.rpc.server.provider;

import cn.llyong.rpc.common.config.MonkeyRpcProperties;
import cn.llyong.rpc.common.registry.ServiceRegistry;
import cn.llyong.rpc.common.utils.RpcCacheHolder;
import cn.llyong.rpc.server.annotation.RpcService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * @description:
 * @author: lvyong
 * @date: 2020年06月24日 09:25
 */
@Component
public class RpcProvider implements ApplicationContextAware {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private ServiceRegistry serviceRegistry;

    @Autowired
    private MonkeyRpcProperties rpcProperties;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        RpcCacheHolder.APPLICATION_CONTEXT = applicationContext;

        StringBuilder builder = new StringBuilder();
        builder.append(rpcProperties.getGroupName())
                .append("/")
                .append(rpcProperties.getAppName())
                .append("/")
                .append(rpcProperties.getServerIp())
                .append(":")
                .append(rpcProperties.getServerPort());
        String nodePath = builder.toString();
        //注册服务
        serviceRegistry.register(nodePath, "");

        Map<String, Object> beans = applicationContext.getBeansWithAnnotation(RpcService.class);
        for(Object serviceBean : beans.values()){
            Class<?> clazz = serviceBean.getClass();
            Class<?>[] interfaces = clazz.getInterfaces();

            for (Class<?> inter : interfaces){
                //接口的全限定名
                String interfaceName = inter.getName();
                logger.info("加载服务类: {}", interfaceName);
                RpcCacheHolder.PROVIDERS_SERVICES.put(interfaceName, serviceBean);
            }
        }
        logger.info("已加载全部服务接口:{}", RpcCacheHolder.PROVIDERS_SERVICES);
    }
}
